import { CallHandler, ExecutionContext, Injectable, NestInterceptor } from '@nestjs/common'
import { Observable } from 'rxjs'
import { map } from 'rxjs/operators'
import { ErrorCode } from '@/shared/constants/error.constants'

export interface Response {
  statusCode: number
  message: string
}

@Injectable()
export class ResponseInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    return next.handle().pipe(
      map((data) => {
        const newData = data as any

        if (!newData?.response) {
          return {
            data: newData,
            code: ErrorCode.SUCCESS.CODE,
            msg: ErrorCode.SUCCESS.MESSAGE,
          }
        }

        let code: number, msg: string
        if (ErrorCode.HasCode(newData.response.code)) {
          code = newData.response.code
          msg = newData.message || ErrorCode.CodeToMessage(code)
        } else {
          code = ErrorCode.ERROR.CODE
          msg = newData.message || ErrorCode.ERROR.MESSAGE
        }

        return {
          code,
          msg,
        }
      }),
    )
  }
}
